<template>
    <div class="l-rblock" >
        <div v-show="steps(0)" class="l-rblock" style="padding:24px;" >
            <div class="l-page-panel" >
                <el-form :model="formData" :rules="rules" size="mini"  ref="baseInfo" label-width="80px" >
                    <el-col :span="24">
                        <el-form-item label="名称" prop="f_Name">
                            <el-input v-model="formData.f_Name"></el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :span="24">
                        <el-form-item label="图标" prop="f_Icon">
                            <l-input-icon onlyFirst v-model="formData.f_Icon" >
                            </l-input-icon>
                        </el-form-item>
                    </el-col>
                    <el-col :span="24">
                        <el-form-item label="颜色"  prop="f_Color" >
                            <l-input-color v-model="formData.f_Color"
                                    placeholder="请输入"></l-input-color>
                        </el-form-item>
                    </el-col>
                    <el-col :span="24">
                        <el-form-item label="表单选择" prop="f_FormCode">
                            <l-custmerform-select
                                v-model="formData.f_FormCode"
                                @change="custmerformChange"
                                placeholder="请选择"
                                >
                            </l-custmerform-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="24">
                        <el-form-item label="表单版本" prop="f_FormVerison">
                            <l-select
                                v-model="formData.f_FormVerison"
                                :options="formVerisons"
                                placeholder="请选择"
                                >
                            </l-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="24" >
                        <el-form-item label="分类" prop="f_Type">
                            <el-select v-model="formData.f_Type" placeholder="请选择分类">
                                <el-option
                                v-for="item in lr_dataItem['function']"
                                :key="item.f_ItemValue"
                                :label="item.f_ItemName"
                                :value="item.f_ItemValue">
                                </el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="24">
                        <el-form-item label="排序" prop="f_SortCode">
                            <el-input-number v-model="formData.f_SortCode"  controls-position="right" :min="1" ></el-input-number>
                        </el-form-item>
                    </el-col>
                    <el-col :span="24">
                        <el-form-item label="状态" >
                                <el-switch
                                :active-value="1"
                                :inactive-value="0"
                                v-model="formData.f_EnabledMark"
                                >
                            </el-switch>
                        </el-form-item>
                    </el-col>                 
                </el-form>
            </div>
        </div>
        <div v-show="steps(1)" class="l-rblock">
            <l-layout class="l-tab-page" >
                <l-panel >
                    <div class="l-auto-window" >
                        <el-tabs v-model="pageActiveName" :stretch="true" >
                            <el-tab-pane :label="$t('列表设置')" name="tab01">
                                <webcode-columns  ref="columnsOp" :columnsTree="columnsTree"></webcode-columns>
                            </el-tab-pane>
                            <el-tab-pane :label="$t('查询设置')" name="tab02">
                                <webcode-query  ref="queryOp" :queryTree="queryTree" ></webcode-query>
                            </el-tab-pane>
                            <el-tab-pane :label="$t('按钮设置')" name="tab03">
                                <webcode-btns :formType="(formScheme && formScheme.formType==1)?1:0"  ref="btnOp" ></webcode-btns>
                            </el-tab-pane>
                        </el-tabs>
                    </div>
                </l-panel>
            </l-layout>
        </div>
    </div>
</template>
<script>
const api = window.$api.custmerForm.scheme

import webcodeColumns from './config/columns'
import webcodeQuery from './config/query'
import webcodeBtns from './config/btns'

export default {
    provide () {
        return {
            formConfig: this.config
        };
    },
    props: {
        stepActive:{
            type:Number,
            default:0
        }
    },
    components: {
        webcodeColumns,
        webcodeQuery,
        webcodeBtns
    },
    data(){
        return {
            pageActiveName:'tab01',
            columnsTree:[
                {
                    label:'全选',
                    children:[]
                }
            ],
            queryTree:[
                {
                    label:'全选',
                    children:[]
                }
            ],
            colslist:[],
            config:{
                btns:[
                    {label:'新增',id:'Add',prop:'Add',isRowBtn:false},
                    {label:'编辑',id:'Edit',prop:'Edit',isRowBtn:true},
                    {label:'删除',id:'Delete',prop:'Delete',isRowBtn:true},
                    {label:'详情',id:'Details',prop:'Details',isRowBtn:true},
                ],
                table:{
                    columns:[],
                    querys:[],
                    sidx:'',
                    isDESC:false,
                }
            },
            formData:{
                f_Name: '',
                f_Type: '',
                f_Icon: 'learun-icon-stars',
                f_Color:'#3c9cff',
                f_EnabledMark:1,
                f_SortCode: '',
                f_Url: '',
                f_IsSystem:2,
                f_FormCode:'',
                f_FormVerison:''
            },
            rules: {
                f_Name: [
                    { required: true, message: '请输入名称',trigger: 'blur' }
                ],
                f_Icon: [
                    { required: true, message: '请选择图标',trigger: 'blur' }
                ],
                f_Color: [
                    { required: true, message: '请选择颜色',trigger: 'blur' }
                ],
                f_FormCode: [
                    { required: true, message: '请选择表单',trigger: 'blur' }
                ],
                f_FormVerison: [
                    { required: true, message: '请选择表单版本'}
                ],
                f_Type: [
                    { required: true, message: '请选择分类'}
                ],
            },
            formScheme:null
        };
    },
    asyncComputed:{
      formVerisons:{
        async get(){
            let res = []
            if(!this.$validatenull(this.formData.f_FormCode)){
              res = await this.$awaitWraper(api.getHistoryList(this.formData.f_FormCode))
            }
            return (res || []).map(t=>{return {label:this.lr_dateFormat(t.f_CreateDate),value:t.f_Id }})
        }
      }
    },
    methods:{
        steps(num){
            return this.stepActive == num
        },
        custmerformChange(val){
            if(val == null){
                this.formData.f_FormVerison = ''
            }
            else{
                this.formData.f_FormVerison = val.f_SchemeId
            }            
        },
        // 表单验证
        validateSteps(){
            return new Promise((resolve) => {
                this.$refs.baseInfo.validate(async(valid) => {
                    if(valid){
                        const {f_Scheme} = (await this.$awaitWraper(api.getHistory(this.formData.f_FormVerison))) || {}

                        this.formScheme = JSON.parse(f_Scheme)

                        if(this.formScheme.formType == 1){// 如果是视图表单就关闭部分按钮
                            this.config.btns = this.config.btns.filter(t=>['Import','Export','Details'].includes(t.id))
                        }

                        const columns = []
                        this.formScheme.formInfo.tabList.forEach(tab=>{
                            columns.push(...tab.components.filter(t=>!['gridtable','divider','password','viewtable','card','btn'].includes(t.type)))
                        })

                        this.columnsTree[0].children = columns.map(t=>{return {id:t.prop,prop:t.prop,label:t.label, width:120,align:'left'}})

                        // 1.获取表格列
                        // 2.过滤掉已选列中在表格列中找不到的列
                        let columnsChecked =  this.config.table.columns.filter(t=> this.columnsTree[0].children.findIndex(t2=>t2.prop == t.prop) != -1)
                        this.config.table.columns = columnsChecked;


                        this.queryTree[0].children = columns.filter(t=>!['upload','uploadimg','password','timerange','datetimerange'].includes(t.type)).map(t=>{return {id:t.prop,prop:t.prop,label:t.label}});
                        let queryChecked =  this.config.table.querys.filter(t=> this.queryTree[0].children.findIndex(t2=>t2.prop == t.prop) != -1)
                        this.config.table.querys = queryChecked;

                    

                        this.colslist = columns.map(t=>{return {value:t.prop,label:t.label}});


                        this.$nextTick(()=>{
                            this.$refs.columnsOp.setCheckedKeys(columnsChecked.map(t=>t.prop));
                            this.$refs.queryOp.setCheckedKeys(queryChecked.map(t=>t.prop));
                            this.$refs.btnOp.setCheckedKeys(this.config.btns.map(t=>t.id));
                        })
                    
                    }
                    resolve(valid)
                })
            })
        },

        // 表单方法
        resetForm(){
            this.pageActiveName = 'tab01'
            this.formData.f_SchemeId  = ''
            this.$refs.baseInfo && this.$refs.baseInfo.resetFields()
            this.config.btns = [
                {label:'新增',id:'Add',prop:'Add',isRowBtn:false},
                {label:'编辑',id:'Edit',prop:'Edit',isRowBtn:true},
                {label:'删除',id:'Delete',prop:'Delete',isRowBtn:true},
                {label:'详情',id:'Details',prop:'Details',isRowBtn:true},
            ]
            this.config.table = {
                columns:[],
                querys:[],
                sidx:'',
                isDESC:false,
            }
        },
        setForm(data){
            this.formData = data
            const scheme = JSON.parse(data.scheme)
            this.config.btns = scheme.btns
            this.config.table = scheme.table
        },
        getForm(){
            const postData = {}

            const formData =  this.$deepClone(this.formData)
            formData.scheme = JSON.stringify(this.$deepClone(this.config))

            postData.moduleItemEntitys = []
            this.config.btns.forEach(btn=>{
                postData.moduleItemEntitys.push({f_Code:btn.prop,f_Name:btn.label,f_Type:1})
            })

            const componentMap = {}
            this.formScheme.formInfo.tabList.forEach(tab => {
                tab.components.forEach(component =>{
                    componentMap[component.prop] = component
                    if(!['gridtable','divider','card'].includes(component.type) && component.display){
                        postData.moduleItemEntitys.push({f_Code:component.prop,f_Name:component.label,f_Type:3})
                    }
                    else if(['gridtable'].includes(component.type)){
                        postData.moduleItemEntitys.push(...component.children.map(t=>{
                            return {
                                f_Code:`${component.prop}|${t.prop}`,
                                f_Name:`${component.label || '表格'}-${t.label}`,
                                f_Type:3
                            }
                        }))
                        
                        postData.moduleItemEntitys.push({
                            f_Code:`${component.prop}_add`,
                            f_Name:`${component.label || '表格'}-添加按钮`,
                            f_Type:3
                        })

                        postData.moduleItemEntitys.push({
                            f_Code:`${component.prop}_remove`,
                            f_Name:`${component.label || '表格'}-删除按钮`,
                            f_Type:3
                        })
                    }
                    else if(['divider'].includes(component.type)){
                        postData.moduleItemEntitys.push({f_Code:component.prop,f_Name:`${component.label}-${component.html}`,f_Type:3 })
                    }
                })
            })

            this.config.table.columns.forEach(column=>{
                const columnComponent = componentMap[column.prop]
                const enCode = `${columnComponent.field}${this.formScheme.formType==1?'':this.formScheme.db.findIndex(t=>t.name == columnComponent.table)}`
                postData.moduleItemEntitys.push({f_Code:enCode,f_Name:column.label,f_Type:2})
            })



            postData.functionEntity = formData

            return postData
        },
    }
}
</script>